# -*- coding:utf-8 -*
import Image
import math
import StringIO
import urllib2

class Pic:
    _height = None
    _width  = 225
    _img_id = None
    _im = None
    
    _new_img = None
    def __init__(self, img_url):
        try:
		    urlopen = urllib2.urlopen(img_url)
		    data = urlopen.read()
        except Exception as e:
            raise Exception("img")
        try:
            self._im = Image.open(StringIO.StringIO(data))
        except Exception as e:
            raise Exception("isno")
        
        if self._im.mode != "RGB":
            self._im = self._im.convert("RGB")
        x,y = self._im.size
        self._height = int((225.0/x)*y)
        self._new_img = self._imgResize(self._im, self._width, self._height)
    def save(self, id):
        try:
            self._new_img.save("pics/"+str(id)+"_225x"+str(self._height)+'.jpg',"JPEG",quality=95,optimize=True)
        except Exception,e:
            raise Exception(e)
    def getHeight(self):
        return self._height
    
    def _imgResize(self, im ,width, height):
        try:
            im_w,img_h = self._im.size
            rats = width / (height * 1.0)
            w_rats = im_w / (img_h * 1.0)
            h_rats = img_h / (im_w * 1.0)
            if height>img_h:
                height = img_h
            
            if width>im_w:
                width = im_w

            if im_w>(img_h*rats):
                delta = ( int(math.ceil(height * w_rats)),height)
            else:
                delta = (width,int(math.ceil(width* h_rats)))
            try:
                self._im.thumbnail((delta),Image.ANTIALIAS)
            except:
                raise Exception("isnono")
            nw,nh = self._im.size
            if im_w>(img_h*rats):
                left = (nw - width)/ 2
                box = (left, 0, left+width, height)
            else:
                top = (nh - height)/2
                box = (0, top, width, top+height)
            return self._im.crop(box)
        except :
            return None
        
    def getContent(self):
		output = StringIO.StringIO()
		self._new_img.save(output,"JPEG", quality = 95, optimize = True)
		content = output.getvalue()
		output.close()
		return content
